package com.csx.governance.traffic.mq.rocketmq;

import com.csx.governance.traffic.mq.rocketmq.hook.TrafficProduceMessageHook;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;

/**
 * 在此处对生产者进行处理
 * @author cuisongxu
 * @date 2023/2/28 16:31
 */
public class TrafficMQProducerBeanPostProcessor implements BeanPostProcessor {

    private final ApplicationContext applicationContext;

    public TrafficMQProducerBeanPostProcessor(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        if(bean instanceof DefaultMQProducer) {

            DefaultMQProducer producer = (DefaultMQProducer) bean;
            TrafficProduceMessageHook trafficProduceMessageHook = applicationContext.getBean(TrafficProduceMessageHook.class);
            // 注册发送消息的钩子,该钩子会在 消息消费前 和 消息消费后 回调其钩子方法
            producer.getDefaultMQProducerImpl().registerSendMessageHook(trafficProduceMessageHook);
        }
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}
